package com.ruoyi.payments.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.payments.domain.Payments;
import com.ruoyi.payments.mapper.PaymentsMapper;
import com.ruoyi.payments.service.IPaymentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 支付Service业务层处理（带Redis缓存）
 */
@Service
public class PaymentsServiceImpl implements IPaymentsService {
    private static final String PAYMENT_KEY_PREFIX = "payment:";
    private static final String PAYMENT_LIST_KEY_PREFIX = "payment:list:";
    private static final Integer CACHE_EXPIRE_TIME = 10; // 支付记录缓存时间较短(10分钟)

    @Autowired
    private PaymentsMapper paymentsMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询支付记录（带缓存）
     */
    @Override
    public Payments selectPaymentsByPaymentId(Long paymentId) {
        return paymentsMapper.selectPaymentsByPaymentId(paymentId);

    }

    /**
     * 查询支付列表（带缓存）
     */
    @Override
    public List<Payments> selectPaymentsList(Payments payments) {
        // 生成缓存key，基于查询条件
        String key = PAYMENT_LIST_KEY_PREFIX + payments.getUserName();

        // 先从缓存获取
        List<Payments> cachedList = redisCache.getCacheList(key);
        if (cachedList != null && !cachedList.isEmpty()) {
            return cachedList;
        }

        // 缓存没有则查询数据库
        List<Payments> paymentList = paymentsMapper.selectPaymentsList(payments);

        if (paymentList != null && !paymentList.isEmpty()) {
            // 存入缓存，支付记录缓存时间较短
            redisCache.setCacheList(key, paymentList);
            redisCache.expire(key, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        }

        return paymentList;
    }

    /**
     * 新增支付记录（同步缓存）
     */
    @Override
    public int insertPayments(Payments payments) {
        int result = paymentsMapper.insertPayments(payments);
        if (result > 0) {
            // 清除相关的列表缓存（按用户名清除）
            clearUserPaymentListCache(payments.getUserName());
            // 缓存新创建的支付记录
            String key = PAYMENT_KEY_PREFIX + payments.getUserName();
            redisCache.setCacheObject(key, payments, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        }
        return result;
    }

    /**
     * 修改支付记录（同步缓存）
     */
    @Override
    public int updatePayments(Payments payments) {
        int result = paymentsMapper.updatePayments(payments);
        if (result > 0) {
            // 更新单个支付记录缓存
            String key = PAYMENT_KEY_PREFIX + payments.getUserName();
            redisCache.setCacheObject(key, payments, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
            // 清除相关的列表缓存（按用户名清除）
            clearUserPaymentListCache(payments.getUserName());
        }
        return result;
    }

    /**
     * 批量删除支付记录（同步缓存）
     */
    @Override
    public int deletePaymentsByPaymentIds(Long[] paymentIds) {
        // 先获取所有要删除的支付信息项的用户名
        Set<String> userNames = new HashSet<>();
        for (Long paymentId : paymentIds) {
            Payments payments = paymentsMapper.selectPaymentsByPaymentId(paymentId);
            if (payments != null) {
                userNames.add(payments.getUserName());
            }
        }
        int result = paymentsMapper.deletePaymentsByPaymentIds(paymentIds);

        if (result > 0) {
            // 清除相关用户的列表缓存
            for (String userName : userNames) {
                clearUserPaymentListCache(userName);
            }
        }
        return result;
    }

    /**
     * 删除支付记录（同步缓存）
     */
    @Override
    public int deletePaymentsByPaymentId(Long paymentId) {
        // 先查询支付记录获取userName
        Payments payment = paymentsMapper.selectPaymentsByPaymentId(paymentId);
        int result = paymentsMapper.deletePaymentsByPaymentId(paymentId);
        if (result > 0 && payment != null) {
            // 清除相关用户的列表缓存
            clearUserPaymentListCache(payment.getUserName());
        }
        return result;
    }

    /**
     * 清除用户支付列表缓存
     */
    private void clearUserPaymentListCache(String userName) {
        if (userName != null) {
            // 清除普通列表缓存
            redisCache.deleteObject(PAYMENT_KEY_PREFIX + userName);
            // 清除带详情的列表缓存
            redisCache.deleteObject(PAYMENT_LIST_KEY_PREFIX + userName);
        }
    }
}